//
//  OrderDetailViewController.swift
//  Box
//
//  Created by mn on 2025/4/1.
//

import UIKit

class OrderDetailViewController: BaseViewController{

    private let tableView = UITableView()

    let orderModel:OrderModel
    init(orderModel: OrderModel) {
        self.orderModel = orderModel
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        nav.title = "订单详情"

        tableView.backgroundColor = .fromHex("#F4F6F8")
        view.addSubview(tableView)
        view.bringSubviewToFront(nav)
        tableView.dataSource = self
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        tableView.contentInsetAdjustmentBehavior = .never
        let headerView = OrderDetailHeaderView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 267+30))
        tableView.tableHeaderView = headerView
        headerView.stateLabel.text = orderModel.statusDesc
        headerView.addressView.nameLabel.text = orderModel.name
        headerView.addressView.phoneLabel.text = orderModel.mobile
        headerView.addressView.addressLabel.text = orderModel.addressPathDes + orderModel.detailAddress
        headerView.descLabel.text = orderModel.goodsName + "等\(orderModel.count)件商品"
        tableView.tableFooterView = UIView()
        tableView.registerCells([OrderDetailGoodsCell.self,
                                 OrderDetailInfoCell.self])
        getOrderDetail()
    }
    var orderDetailModel: OrderDetailModel?
    func getOrderDetail() {
        APIService.request(api: .orderDetail(orderId: orderModel.id)) {
            [weak self] (result, response) in
            self?.tableView.endAllRefreshing()
            if result.success, let model: OrderDetailData = Decoder.data(response) {
                self?.orderDetailModel = model.data
                self?.tableView.reloadData()
            }
        }
    }
}
extension OrderDetailViewController: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        2
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            let cell: OrderDetailGoodsCell = tableView.cell(indexPath)
            cell.configure(with: orderModel)
            return cell
        }
        let cell: OrderDetailInfoCell = tableView.cell(indexPath)
        cell.configure(with: orderDetailModel)
        return cell
    }
}
